package isquirrel.servlets;

import isquirrel.Logger;
import isquirrel.QueuePool;
import isquirrel.UserManager;
import isquirrel.beans.Url;
import isquirrel.beans.User;
import isquirrel.beans.UserLike;
import isquirrel.error.CannotLoginUserException;
import isquirrel.servlets.handler.HttpDBServlet;

import java.io.IOException;

import javax.servlet.ServletException;

import org.json.JSONException;

/**
 * Servlet implementation class iLike
 */
public class iLike extends HttpDBServlet {
	private static final long serialVersionUID = 1L;

    /**
     * Default constructor. 
     */
    public iLike() {
    }
    
    private String sourceToString(int source) {
    	switch (source) {
    		case 0: return "bookmarklet"; 
    		case 1: return "recommender"; 
    		case 2: return "friends"; 
    		case 3: return "others";
    	}
    	return "unknown";
    }


	@SuppressWarnings("unchecked")
	@Override
	protected void handleGet() throws ServletException, IOException,
			JSONException, CannotLoginUserException {
		
		String userToken = request.getParameter("t"); 			//token
		String auth_method = request.getParameter("au");        //authentication method 
		String user = request.getParameter("user");  			//username
		String likedURL = request.getParameter("url");          //liked url
		String title = request.getParameter("title");           //page title
		Integer source = Integer.parseInt(request.getParameter("source"));           //page source
		
		boolean loggedin = false;
		boolean istoken = false;
		
		//HibernateUtil.beginTransaction();
		if (auth_method != null){
			if (auth_method.equals("to")){
				loggedin = UserManager.tokenLogin(user,userToken);
				istoken=true;
			}
			else if (auth_method.equals("site")){
				loggedin = true;
			}
			
			if (loggedin) {
				User u = null;
				if (istoken){
					u  = UserManager.getUser(user);
				}
				else{
					u = getLoggedInUser();
				}
				
				String thumb = "";
				int type = 0;
				if (likedURL.contains("youtube.com")){
					thumb = "youtube.png";
					type = 0;
				}
				else if (likedURL.contains("last.fm")){
					thumb = "lastfm.png";
					type = 1;
				}
				else{
					thumb = "wikipedia.png";
					type = 2;
				}
				
				//convert en. to www. on wikipedia urls
				if (likedURL.contains("en.wikipedia")) {
					likedURL = likedURL.replaceFirst("en\\.wikipedia", "www.wikipedia");
				}

				Url url = new Url(title, likedURL);
				url.setThumb(thumb);
				url.setLiked(true);
						
				//store the url in the database given the user has not already liked the page 
				if (u.addUrl(url) == -1){
					if (istoken){
						response.getWriter().print("<div style='display:block; height:40px; width:430px; background-image:url(http://websquirrel.net/iSquirrel/images/attention.png); background-repeat:no-repeat; padding:7px 0px 0px 37px; font-family:Lucida Grande; font-size:1.15em'>Sorry, but you have already liked this page.</div>");
					}
					return;
				}

				if (type == 0){
					Logger.log(u, "liked video from " + sourceToString(source));
					//props = ytapi.getProperties(likedURL);
				}
				else if (type == 1){
					Logger.log(u, "liked music from " + sourceToString(source));
					//props = lfmapi.getProperties(likedURL);
				}
				else{
					Logger.log(u, "liked page from " + sourceToString(source));
					UserLike ul = new UserLike(u.getUsername(), likedURL);
					QueuePool.getQueue("like").add(ul);
				
				}
				
				if (istoken){
					response.getWriter().print("<div style='display:block; height:40px; width:430px; background-image:url(http://websquirrel.net/iSquirrel/images/ok.png); background-repeat:no-repeat; padding:7px 0px 0px 37px; font-family:Lucida Grande; font-size:1.15em'>Good, the page has been saved.</div>");
				}
				
				
			}
			else {
				response.getWriter().print("<div style='display:block; height:40px; width:430px; background-image:url(http://websquirrel.net/iSquirrel/images/error.png); background-repeat:no-repeat; padding:7px 0px 0px 37px; font-family:Lucida Grande; font-size:1.15em'>An error occured. Please try again.</div>");
				throw new CannotLoginUserException();
			}
		}
		else {
			response.getWriter().print("<div style='display:block; height:40px; width:430px; background-image:url(http://websquirrel.net/iSquirrel/images/error.png); background-repeat:no-repeat; padding:7px 0px 0px 37px; font-family:Lucida Grande; font-size:1.15em'>An error occured. Please try again.</div>");
			throw new CannotLoginUserException();
		}
	}

	@Override
	protected void handlePost() throws ServletException, IOException, CannotLoginUserException, 
			JSONException {

		
	}

}
